﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;

namespace BasicMachine
{
    public partial class Form1
    {
        //bool m_StopWorking = false;
        //bool m_LimitWorking = false;

        const string ShortEnter = "SE";
        const string ShortExit = "SX";
        const string LongEnter = "LE";
        const string LongExit = "LX";

        const string MARKET = "Market";
        const string LIMIT = "Limit";
        const string STOP = "Stop";

        [DllImport(@"C:\JihSun\HTS2\Dll\HTSAPITradeClient.dll")]

        static extern void HTSOrder([MarshalAs(UnmanagedType.LPStr)] String msg);

        private void StrategyMaster(List<string>info)
        {
            string OrderType;
            string Price="0";
            string BuySell="";
            string OpenCloseAuto= "O";
            string[] order = info[2].Split(' ');
            int orderAmount = Convert.ToInt32(order[1]);

            if (info.Count < 6)
            {
                foreach (Methods mob in methodOB)
                {
                    if (mob.Enable != false)
                    {
                        if (info[3].Contains(mob.Method_Name) && mob.Limit_Index != 0 && mob.Stop_Index != 0)
                        {
                            string[] changeOrder = info[2].Split(' ');
                            if (changeOrder[changeOrder.Length - 1] == STOP)
                            {
                                int cPrice = Convert.ToInt32(changeOrder[3]);
                                if (mob.Stop_Index != cPrice)
                                {
                                    mob.Stop_Index = cPrice;
                                    SendAccSMS(mob);
                                    saveToXML();
                                }
                            }
                            //else if (changeOrder[changeOrder.Length - 1] == LIMIT)
                            //{
                            //    int cPrice = Convert.ToInt32(changeOrder[3]);
                            //    if (mob.Limit_Index != cPrice)
                            //    {
                            //        mob.Limit_Index = cPrice;
                            //        saveToXML();
                            //    }
                            //}
                        }

                        if (info[3].Contains(mob.Method_Name) && mob.excuteMonth != 0 && (mob.Limit_Index == 0 || mob.Stop_Index == 0))
                        {
                            if (mob.SpecialRule == "trail" && mob.Stop_Index == 0)
                            {
                                if (info[1] == ShortExit)
                                    BuySell = "B";
                                else if (info[1] == LongExit)
                                    BuySell = "S";
                                else
                                    break;

                                if (order[order.Length - 1] == STOP)
                                {
                                    Price = order[3];
                                    mob.Stop_Index = Convert.ToInt32(Price);
                                    mob.OrderPlaceDate = DateTime.Now.ToString();

                                    string eBody = "";
                                    string SMString = ReturnSM(mob, "A", BuySell, "L", ref eBody);

                                    foreach (Accounts acc in accountList)
                                    {
                                        if (acc.strategys.Contains(mob.Method_Name) && acc.Enable && acc.PhoneNumber != "none")
                                        {
                                            SMSender.sendMessage("訊號單", SMString, "", acc.PhoneNumber);

                                            if (acc.email != "none")
                                            {
                                                AlertMail.MailSubject = "OrderPlace";
                                                AlertMail.MailBody = eBody;
                                                AlertMail.MailTo = acc.email;
                                                AlertMail.Send();
                                            }
                                        }
                                    }
                                }
                                saveToXML();
                            }
                            else if (info[1].Contains(mob.SpecialRule) || mob.SpecialRule == "none")
                            {
                                if (info[1] == ShortExit)
                                    BuySell = "B";
                                else if (info[1] == LongExit)
                                    BuySell = "S";
                                else
                                    break;

                                


                                if (order[order.Length - 1] == LIMIT && mob.Limit_Index == 0)
                                {
                                    OrderType = "L";
                                    Price = order[3];
                                    mob.Limit_Index = Convert.ToInt32(Price);
                                    OpenCloseAuto = "A";
                                    mob.OrderPlaceDate = DateTime.Now.ToString();

                                    PlaceOrder(mob, OpenCloseAuto, BuySell, OrderType, mob.Limit_Index, "N", 'R',false);
                                }
                                else if (order[order.Length - 1] == STOP)
                                {
                                    Price = order[3];
                                    mob.Stop_Index = Convert.ToInt32(Price);
                                    mob.OrderPlaceDate = DateTime.Now.ToString();

                                    if (mob.Limit_Index != 0 )
                                    {
                                        string eBody = "";
                                        string SMString = ReturnSM(mob, "A", BuySell, "L", ref eBody);

                                        foreach (Accounts acc in accountList)
                                        {
                                            if (acc.strategys.Contains(mob.Method_Name) && acc.Enable && acc.PhoneNumber != "none")
                                            {
                                                SMSender.sendMessage("訊號單", SMString, "", acc.PhoneNumber);

                                                if (acc.email != "none")
                                                {
                                                    AlertMail.MailSubject = "OrderPlace";
                                                    AlertMail.MailBody = eBody;
                                                    AlertMail.MailTo = acc.email;
                                                    AlertMail.Send();
                                                }
                                            }
                                        }
                                    }
                                }
                                saveToXML();
                            }
                            break;
                        }
                    }
                }
            }
            else
            {
                foreach (Methods mob in methodOB)
                {
                    if (mob.Enable != false)
                    {
                        if (info[7].Contains(mob.Method_Name))
                        {
                            if (info[1].Contains(mob.SpecialRule) || mob.SpecialRule == "none" || mob.SpecialRule == "market" || mob.SpecialRule=="trail")
                            {
                                if (info[1] != ShortExit && info[1] != LongExit)
                                {
                                    //    mob.excuteMonth = 0;
                                    //    mob.Limit_Index = 0;
                                    //    mob.Stop_Index = 0;
                                    //}
                                    //else
                                    //{
                                    OpenCloseAuto = "O";
                                    OrderType = "M";

                                    if (info[1] == LongEnter)
                                    {
                                        BuySell = "B";
                                        mob.Current_Hold = orderAmount;
                                    }
                                    else if (info[1] == ShortEnter)
                                    {
                                        BuySell = "S";
                                        mob.Current_Hold = -orderAmount;
                                    }
                                    mob.excuteMonth = GetContractDate();
                                    mob.OrderPlaceDate = DateTime.Now.ToString();

                                    PlaceOrder(mob, OpenCloseAuto, BuySell, OrderType, 0, "N", 'F',false);
                                }
                                else if (mob.SpecialRule == "trail")
                                {
                                    if (info[1] == LongExit)
                                        BuySell = "S";
                                    else if (info[1] == ShortExit)
                                        BuySell = "B";

                                    PlaceOrder(mob, "A", BuySell, "M", 0, "N", 'F', false);
                                    mob.Current_Hold = 0;
                                    mob.Stop_Index = 0;
                                    mob.Limit_Index = 0;
                                    mob.excuteMonth = 0;
                                    mob.OrderPlaceDate = "";
                                }
                                else if (mob.SpecialRule == "market")
                                {
                                    if (info[1] == LongExit)
                                        BuySell = "S";
                                    else if (info[1] == ShortExit)
                                        BuySell = "B";

                                    PlaceOrder(mob, "A", BuySell, "M", 0, "N", 'F', false);
                                    mob.Current_Hold = 0;
                                    mob.excuteMonth = 0;
                                    mob.OrderPlaceDate = "";
                                }
                                else
                                {
                                    if (info[1] == ShortExit && info[2].Contains("Stop"))
                                    {
                                        PlaceOrder(mob, "A", "B", "M", 0, "N", 'F', false);
                                        mob.Current_Hold = 0;
                                        mob.Stop_Index = 0;
                                        mob.Limit_Index = 0;
                                        mob.excuteMonth = 0;
                                        mob.OrderPlaceDate = "";
                                    }
                                    else if (info[1] == LongExit && info[2].Contains("Stop"))
                                    {
                                        PlaceOrder(mob, "A", "S", "M", 0, "N", 'F', false);
                                        mob.Current_Hold = 0;
                                        mob.Stop_Index = 0;
                                        mob.Limit_Index = 0;
                                        mob.excuteMonth = 0;
                                        mob.OrderPlaceDate = "";
                                    }
                                    else if (info[1] == ShortExit && info[2].Contains("Limit"))
                                    {
                                        SaveToHistory(mob.Chinese_Name, DateTime.Now.ToString(), "L", mob.Limit_Index, "B", mob.excuteMonth);
                                        LimitDone(mob.Chinese_Name, mob.Method_Name, "B", mob.Limit_Index, mob.excuteMonth);
                                        mob.Current_Hold = 0;
                                        mob.Limit_Index = 0;
                                        mob.Stop_Index = 0;
                                        mob.excuteMonth = 0;
                                        mob.OrderPlaceDate = "";
                                    }
                                    else if (info[1] == LongExit && info[2].Contains("Limit"))
                                    {
                                        SaveToHistory(mob.Chinese_Name, DateTime.Now.ToString(), "L", mob.Limit_Index, "S", mob.excuteMonth);
                                        LimitDone(mob.Chinese_Name, mob.Method_Name, "S", mob.Limit_Index, mob.excuteMonth);
                                        mob.Current_Hold = 0;
                                        mob.Limit_Index = 0;
                                        mob.Stop_Index = 0;
                                        mob.excuteMonth = 0;
                                        mob.OrderPlaceDate = "";
                                    }
                                }

                                saveToXML();
                                break;
                            }
                        }
                    }
                }
            }
        }

        //private void StopMonitor(int currentIndex)
        //{
        //    bool save = false;

        //    foreach(Methods mob in methodOB)
        //    {
        //        TimeSpan STOPLOSTTIME = new TimeSpan(8, 46, 0);

        //        if ((m_OpeningValue < mob.Stop_Index && mob.Current_Hold > 0) || (m_OpeningValue > mob.Stop_Index && mob.Current_Hold < 0))
        //            STOPLOSTTIME = new TimeSpan(9, 15, 0);


        //        if (DateTime.Now.TimeOfDay >= STOPLOSTTIME)
        //        {
                    
        //            if (mob.Current_Hold < 0 && mob.Stop_Index <= currentIndex && mob.Stop_Index != 0)
        //            {
        //                if (!m_StopWorking)
        //                {
        //                    m_StopWorking = true;
        //                    PlaceOrder(mob, "A", "B", "M", 0, "N", 'F');
        //                    mob.Current_Hold = 0;
        //                    mob.Stop_Index = 0;
        //                    mob.Limit_Index = 0;
        //                    mob.excuteMonth = 0;
        //                    mob.OrderPlaceDate = "";
        //                    save = true;
        //                    m_StopWorking = false;
        //                }
        //            }
        //            else if (mob.Current_Hold > 0 && mob.Stop_Index >= currentIndex)
        //            {
        //                if (!m_StopWorking)
        //                {
        //                    m_StopWorking = true;
        //                    PlaceOrder(mob, "A", "S", "M", 0, "N", 'F');
        //                    mob.Current_Hold = 0;
        //                    mob.Stop_Index = 0;
        //                    mob.Limit_Index = 0;
        //                    mob.excuteMonth = 0;
        //                    mob.OrderPlaceDate = "";
        //                    save = true;
        //                    m_StopWorking = false;
        //                }
        //            }
        //        }
        //    }

        //    if (save)
        //        saveToXML();
        //}

        //private void LimitMonitor(int currentIndex)
        //{
        //    bool save = false;

        //    foreach (Methods mob in methodOB)
        //    {
        //        if (mob.Current_Hold < 0 && mob.Limit_Index >= currentIndex)
        //        {
        //            if (!m_LimitWorking)
        //            {
        //                m_LimitWorking = true;
        //                SaveToHistory(mob.Chinese_Name, DateTime.Now.ToString(), "L", mob.Limit_Index, "B", mob.excuteMonth);
        //                LimitDone(mob.Chinese_Name,mob.Method_Name, "B", mob.Limit_Index, mob.excuteMonth);
        //                mob.Current_Hold = 0;
        //                mob.Limit_Index = 0;
        //                mob.Stop_Index = 0;
        //                mob.excuteMonth = 0;
        //                mob.OrderPlaceDate = "";
        //                save = true;

        //                m_LimitWorking = false;
        //            }
        //        }
        //        else if (mob.Current_Hold > 0 && mob.Limit_Index <= currentIndex && mob.Limit_Index!=0 )
        //        {
        //            if (!m_LimitWorking)
        //            {
        //                m_LimitWorking = true;
        //                SaveToHistory(mob.Chinese_Name, DateTime.Now.ToString(), "L", mob.Limit_Index, "S", mob.excuteMonth);
        //                LimitDone(mob.Chinese_Name, mob.Method_Name, "S", mob.Limit_Index, mob.excuteMonth);
        //                mob.Current_Hold = 0;
        //                mob.Limit_Index = 0;
        //                mob.Stop_Index = 0;
        //                mob.excuteMonth = 0;
        //                mob.OrderPlaceDate = "";
        //                save = true;

        //                m_LimitWorking = false;
        //            }
        //        }
        //    }

        //    if (save)
        //        saveToXML();
        //}

        

        private void PlaceOrder(Methods mob ,  string OpenClose, string BuySell, string OrderType, int Price, string DayTrade, char orderStyle, bool changeMonth)
        {
            string OrderMSG;
            EasyMail OrderMail = new EasyMail();

            OrderMail.MailFrom = "rs.future.studio@gmail.com";
            OrderMail.SMTPPort = 587;
            OrderMail.SMTPPassword = "sanches0528";
            OrderMail.SMTPServer = "smtp.gmail.com";
            OrderMail.SMTPUsername = "rsfuturestudio@gmail.com";
            OrderMail.SMTPSSL = true;

            foreach (Accounts acc in accountList)
            {
                if (acc.strategys.Contains(mob.Method_Name) && acc.Enable)
                {
                    if (acc.orderLot == 0)
                        acc.orderLot = OrderLot(acc.Asset, mob.Minimun_Lot, mob.MID_Value);

                    OrderMSG = "Market=F,Account=";
                    OrderMSG += acc.Number;
                    OrderMSG += ",ContractName=TXF";
                    OrderMSG += ",ContractDate=" + mob.excuteMonth;
                    OrderMSG += ",OpenCloseAuto=" + OpenClose;
                    OrderMSG += ",BuySell=" + BuySell;
                    OrderMSG += ",Lots=" + Math.Abs(mob.Current_Hold * acc.orderLot);
                    OrderMSG += ",OrderType=" + OrderType;
                    OrderMSG += ",Price=" + Price;
                    OrderMSG += ",FokIocRod=" + orderStyle;
                    OrderMSG += ",DayTrade=" + DayTrade;

                    if(acc.Number != "none")
                        HTSOrder(OrderMSG);

                    if (OpenClose == "A" && OrderType =="M")
                        acc.orderLot = 0;
                    
                    
                    if (changeMonth)
                    {
                        string changeOrder = BuySell == "S" ? "B" : "S";
                        OrderMSG = "Market=F,Account=";
                        OrderMSG += acc.Number;
                        OrderMSG += ",ContractName=TXF";
                        OrderMSG += ",ContractDate=" + lab_NextMonth.Text;
                        OrderMSG += ",OpenCloseAuto=O";
                        OrderMSG += ",BuySell=" + changeOrder;
                        OrderMSG += ",Lots=" + acc.orderLot;
                        OrderMSG += ",OrderType=" + OrderType;
                        OrderMSG += ",Price=" + Price;
                        OrderMSG += ",FokIocRod=" + orderStyle;
                        OrderMSG += ",DayTrade=" + DayTrade;

                        if (acc.Number != "none")
                            HTSOrder(OrderMSG);
                    }
                }
            }

            if (changeMonth)
            {
                string emailBody = "開始換月,暫時停損/利,平倉價:" + m_IndexValue + ",新倉價:" + m_NextMonthIndexValue + ",平倉月:" + lab_Month.Text + ",新倉月:" + lab_NextMonth.Text;
                string SMString = "開始換月,暫時停損/利,平倉價:" + m_IndexValue + ",新倉價:" + m_NextMonthIndexValue + ",平倉月:" + lab_Month.Text + ",新倉月:" + lab_NextMonth.Text;

                string mailList = "";
                string phoneList = "";

                foreach (Accounts acc in accountList)
                {
                    if (acc.strategys.Contains(mob.Method_Name) && acc.Enable && acc.PhoneNumber != "none")
                    {
                        phoneList += acc.PhoneNumber + ",";

                        if (acc.email != "none")
                            mailList += acc.email + ",";
                    }
                }

                SMSender.sendMessage("換倉單", SMString, "", phoneList.TrimEnd(','));

                OrderMail.MailSubject = "ChangeMonth";
                OrderMail.MailBody = emailBody;
                OrderMail.MailTo = mailList.TrimEnd(',');
                OrderMail.Send();
            }
            else if (mob.Stop_Index != 0 || OpenClose == "O" || mob.SpecialRule == "market")
            {
                string emailBody = "";

                string SMString = ReturnSM(mob, OpenClose, BuySell, OrderType, ref emailBody);
                string mailList = "";
                string phoneList = "";

                foreach (Accounts acc in accountList)
                {
                    if (acc.strategys.Contains(mob.Method_Name) && acc.Enable && acc.PhoneNumber != "none")
                    {
                        phoneList += acc.PhoneNumber + ",";

                        if (acc.email != "none")
                            mailList += acc.email + ",";
                    }
                }

                SMSender.sendMessage("訊號單", SMString, "", phoneList.TrimEnd(','));

                OrderMail.MailSubject = "OrderPlace";
                OrderMail.MailBody = emailBody;
                OrderMail.MailTo = mailList.TrimEnd(',');
                OrderMail.Send();
            }

            SaveToHistory(mob.Chinese_Name, DateTime.Now.ToString(), OrderType, Price, BuySell, mob.excuteMonth);
          

            //HTSOrder("Market=F,Account=A01-1234567,ContractName=TXF,ContractDate=200808,OpenCloseAuto=A,BuySell=B,Lots=1,OrderType=L,Price=8888,FokIocRod=R,DayTrade=N");
        }

        private void SendAccSMS(Methods mob)
        {
            string mailList = "";
            string phoneList = "";
            string SMS = mob.Chinese_Name + "改停損為" + mob.Stop_Index + ", 停利不變"; 

            foreach (Accounts acc in accountList)
            {
                if (acc.strategys.Contains(mob.Method_Name) && acc.Enable && acc.PhoneNumber != "none")
                {
                    phoneList += acc.PhoneNumber + ",";

                    if (acc.email != "none")
                        mailList += acc.email + ",";
                }
            }

            SMSender.sendMessage("改停損單", SMS, "", phoneList.TrimEnd(','));

            AlertMail.MailSubject = "改停損";
            AlertMail.MailBody = SMS;
            AlertMail.MailTo = mailList.TrimEnd(',');
            AlertMail.Send();
        }

        private string ReturnSM(Methods mob, string OpenClose, string BuySell, string OrderType , ref string eBody)
        {
            string preorder = OrderType == "L" ? "預設" : "停損單成交,";
            string result = OpenClose == "O" ? "訊號做" : "停利:" + mob.Limit_Index + ",停損:" + mob.Stop_Index;
            string action = BuySell == "B" ? "多:" : "空:";
            int currentIndex = lab_Month.Text == mob.excuteMonth.ToString() ? m_IndexValue : m_NextMonthIndexValue;

            string msgBody;

            if (OpenClose != "O")
                msgBody = preorder + result;
            else
                msgBody = result + action + currentIndex;

            if (mob.SpecialRule == "trail" && Math.Abs(currentIndex - mob.Stop_Index) > 10 && OpenClose == "A")
            {
                if (OrderType == "L")
                    msgBody = "停利為移動式, 停損為:" + mob.Stop_Index;
                else
                    msgBody = "移動停利成交";
            }

            string SMString = mob.Chinese_Name + "程式:" + msgBody + ",目前點數:" + currentIndex + ",期貨月份:" + mob.excuteMonth;

            try
            {
                eBody = "Order Signal: " + BuySell;
                eBody = DateTime.Now.TimeOfDay.ToString().Substring(0, 8) + Environment.NewLine;
                eBody += "BuySell:" + BuySell + Environment.NewLine;
                eBody += "Method:" + mob.Method_Name + Environment.NewLine;
                eBody += "OrderType:" + OrderType + Environment.NewLine;
                eBody += "CurrentPoint:" + currentIndex + Environment.NewLine;
                if (OpenClose != "O")
                    eBody += "Stop:" + mob.Stop_Index + ",Limit:" + mob.Limit_Index + Environment.NewLine;

                eBody += SMString;
            }
            catch(Exception e)
            {
            }
            return SMString;
        }



        private void LimitDone(string ChineseName, string MethodName, string BuySell, int Price, int exchangeMonth)
        {
            int currentIndex = lab_Month.Text == exchangeMonth.ToString() ? m_IndexValue : m_NextMonthIndexValue;
            string mailList = "";
            string phoneList = "";

            foreach (Accounts acc in accountList)
            {
                if (acc.strategys.Contains(MethodName) && acc.Enable && acc.PhoneNumber != "none")
                {
                    acc.orderLot = 0;

                    phoneList += acc.PhoneNumber + ",";

                    if (acc.email != "none")
                        mailList += acc.email + ",";
                }
            }


            string action = BuySell == "B" ? "多:" : "空:";
            string SMString = "訊號單: 預掛停利單成交,平倉做" + action + Price + ",目前點數:" + currentIndex + ",期貨月份:" + exchangeMonth;
            
            try
            {

                SMSender.sendMessage(ChineseName + "程式:預掛單成交", SMString, "", phoneList.TrimEnd(','));

                AlertMail.MailSubject = "Pre-Order Gain Complete!";
                AlertMail.MailBody = DateTime.Now.TimeOfDay.ToString().Substring(0, 8) + Environment.NewLine;
                AlertMail.MailBody += "BuySell:" + BuySell + Environment.NewLine;
                AlertMail.MailBody += "Method:" + MethodName + Environment.NewLine;
                AlertMail.MailBody += "OrderType:" + BuySell + Environment.NewLine;
                AlertMail.MailBody += "CurrentPoint:" + currentIndex + Environment.NewLine;
                AlertMail.MailBody += "Limit:" + Price + Environment.NewLine;
                AlertMail.MailBody += SMString;

                AlertMail.MailTo = mailList.TrimEnd(',');
                AlertMail.Send();
            }
            catch (Exception e)
            {
            }
        }

    }
}
